<?php

namespace App\Http\Controllers\Logic;

use App\Http\Controllers\Constant\Constant;
use App\Http\Controllers\Controller;
use App\Http\Controllers\OATrait\OATrait;
use App\Model\OACompany;
use App\Model\OADept;
use App\Model\OAFiles;
use App\Model\OAProjectLx;
use App\Model\OAShenPiLog;
use App\Model\OAStaff;
use App\Model\OAWork;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

/**
 * @desc 审批流程记录
 */
class ApproveHistory extends Controller
{
    use OATrait;

    const SP_COLOR_DEFAULT = '#666';
    const SP_COLOR_APPED = '#409EFF';
    private $specialWork = [9];

    const PROJECT_STATUS_WAIT = 0;
    const PROJECT_STATUS_TODO = 1;
    const PROJECT_STATUS_FINISH = 2;

    //存在返还的流程

    /**
     * @param $id 项目id
     * @param $work_id 流程Id
     * @param $roleid
     * //查审批记录
     */
    public function getApproveHistory($project)
    {
        $gsid = isset($project->gsid) ? $project->gsid : OAProjectLx::query()->where('id', $project->xmid)->value('gsid');
        $gsConfig = $this->getShenPiUserByGsId($gsid);
        //1.查流程线
        $work_link = $this->getWorkLinkByWorkId($project->work_id);
        $history = [];
        $data_all = (new CommonLogic())->getCommonData(['position']);
        $user_all = OAStaff::query()->select(['id', 'account', 'username'])->get()->toArray();
        $user_all = array_column($user_all, null, 'id');
        $position_all = array_column($data_all['position'], 'title', 'id');

        $shenpiLog = [];
        $returnWorkList = config('oa.returnWorkList');
        foreach ($work_link as $work_id => $roleList) {
            try {
                $work_list = isset($returnWorkList[$work_id]) ? $returnWorkList[$work_id] : [];
                $pindex = array_search($project->roleid, $roleList);
                foreach ($roleList as $k => $roleid) {
                    //审批职位
                    $role = $position_all[$roleid];
                    if (empty($work_list)) {
                        $role = $role;
                    } else {
                        $role = $work_id == $returnWorkList[$work_id][0] ? $role : '返还-' . $role;
                    }
                    $history[$work_id][$k]['role'] = $role;
                    //2.查审批记录
                    $roleids = [$roleid];
                    $mapRole = $this->getMapRoleid($roleid);
                    if ($mapRole) $roleids = array_merge($roleids, $mapRole);
                    $shenpiLog = $this->getShenpiLog($project->id, $work_id, $roleids);
                    //销售经理
                    if ($project->work_id == OAWork::WORK_PROJECT_YS && $roleid == Constant::ROLE_SALES_MANAGER) {
                        $staff = Arr::get($user_all, $project->seller_id,[]);
                    } else {
                        $uid = Arr::exists($gsConfig, $roleid) ? Arr::get($gsConfig, $roleid) : $project->uid;
                        $staff = Arr::get($user_all, $uid);
                    }
                    $username = env('APP_ENV') == "local" ? sprintf("%s(%s)", Arr::get($staff, 'username'), Arr::get($staff, 'account')) : Arr::get($staff, 'username','');
                    $color = $project->status == self::PROJECT_STATUS_FINISH ? self::SP_COLOR_APPED : ($k < $pindex ? self::SP_COLOR_APPED : self::SP_COLOR_DEFAULT);
                    $history[$work_id][$k]['username'] = $username;
                    $history[$work_id][$k]['note_list'] = $shenpiLog['note_list'];
                    $history[$work_id][$k]['color'] = $color;
                    $history[$work_id][$k]['file_list'] = $shenpiLog['file_list'];
                }

            } catch (\Exception $e) {
                dump($shenpiLog);
                throw new \Exception('getApproveHistory: ' . $e->getMessage());
            }
        }

        $newHistory = [];
        foreach ($history as $list) {
            foreach ($list as $item) {
                $newHistory[] = $item;
            }
        }
        //dd($newHistory);

        return $newHistory;


    }

    protected function getWorkLinkByWorkId($work_id)
    {
        $logic = new WorkLogic();
        $returnWorkrList = config('oa.returnWorkList');
        if (isset($returnWorkrList[$work_id])) {
            $res = [];
            foreach ($returnWorkrList[$work_id] as $wid) {
                $work_return = $logic->getWorkDetail(['id' => $wid]);
                $work_return_list = array_column($work_return->workList, 'role');
                $res[$wid] = $work_return_list;
            }
            return $res;

        } else {
            $work = $logic->getWorkDetail(['id' => $work_id]);
            $work_list = array_column($work->workList, 'role');
            return [$work_id => $work_list];
        }
    }

    //审批记录
    protected function getShenpiLog($id, $work_id, $role)
    {
        //dd($id,$work_id,$role);

        try {
            $shenpiLogs = OAShenPiLog::query()
                ->where(['work_id' => $work_id, 'pid' => $id])
                ->where('status', '<>', OAShenPiLog::SHENPI_STATUS_NOTHING)
                ->whereIn('roleid', $role)
                ->select(['spuid', 'note', 'status', 'created_at', 'id'])
                ->orderBy("created_at","ASC")
                ->orderByDesc('status')
                ->get()
                ->toArray();
            if (!$shenpiLogs) return ['username' => '', 'note_list' => [], 'color' => self::SP_COLOR_DEFAULT, 'file_list' => []];
            $username = OAStaff::query()->where('id', $shenpiLogs[0]['spuid'])->value('username');
            $color = $username ? self::SP_COLOR_APPED : self::SP_COLOR_DEFAULT;//
            $note_list = [];
            $status_list = OAShenPiLog::SHENPI_STATUS_NAMES;
            $editCount = 1;
            foreach ($shenpiLogs as $index => $log) {
                $statusName = Arr::get($status_list, $log['status']);
                if (Arr::get($log, 'status') == self::PROJECT_STATUS_FINISH) {
                    $statusName .= $editCount;
                    $editCount++;
                }
                $note_list[] = '[' . $statusName . ']' . $log['note'] . ' , ' . $log['created_at'];
            }
            $file_id_list = array_column($shenpiLogs, 'id');
            $file_list = $this->getFileList($file_id_list, FILE_LOG);
            if (empty($file_list)) $file_list = [];

            return ['username' => $username, 'note_list' => $note_list, 'color' => '', 'file_list' => $file_list];
        } catch (\Exception $e) {
            throw new \Exception('getShenpiLog: ' . $e->getMessage());
        }
    }

    //审批文件
    protected function getShenpiFile($id, $work_id, $role)
    {

    }

    //获取公司审批人员
    public function getShenPiUserByGsId($gsid)
    {
        $position_list = config('oa.position');

        $field = [];
        foreach ($position_list as $role => $roleName) {
            $field[] = "{$roleName} AS $role";
        }

        $gsConfig = OACompany::query()->where('id', $gsid)->select($field)->first();

        return $gsConfig->getAttributes();

    }

}
